import { provide, inject, reactive, createApp, h, toRefs } from "vue";
import Loading from './loading.vue'
const LoadingSymbol = Symbol();

const state = reactive({
    show: false, // loading元素是否显示
    text: "正在加载",
});

let [loadingTimer, loadingVM, loadingWrapper] = [null, null, null];
console.log(Loading);
const _loading = (text) => {
    state.show = true;
    if (typeof text === "string") {
        state.text = text;
    }
    if (!loadingVM) {
        // 如果loading实例存在则不重新创建
        loadingVM = createApp(Loading, toRefs(state));
    }

    if (!loadingWrapper) {
        // 如果该节点以经存在则不重新创建
        loadingWrapper = document.createElement("div");
        loadingWrapper.id = "sf-loading";
        document.body.appendChild(loadingWrapper);
        loadingVM.mount("#sf-loading");
    }
};
_loading.close = () => {
    state.show = false;
    state.text = "正在加载";
}

export function provideLoading(config = {}) {
    for (const key in config) {
        globalConfig[key] = config[key];
    }
    provide(LoadingSymbol, _loading);
}

export function useLoading() {
    const loading = inject(LoadingSymbol);
    if (!loading) {
        throw new Error("error");
    }
    return loading;
}
